package cn.xdj.blue.java.netty5.simple.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;


public class Netty5SocketClient implements Runnable {
	private String ip;
	private int port;

	public Netty5SocketClient(String ip, int port) {
		this.ip = ip;
		this.port = port;
	}

	public void run() {
		System.out.println("---访问"+ip+"："+port);
		EventLoopGroup work = new NioEventLoopGroup();
		Bootstrap client = new Bootstrap();
		try {
			client.group(work)
				.channel(NioSocketChannel.class)
				.option(ChannelOption.TCP_NODELAY, true)
				.handler(new ChannelInitializer<SocketChannel>() {

						@Override
						protected void initChannel(SocketChannel arg)
								throws Exception {
							System.out.println("--客户端连接成功--");
							/*arg.pipeline().addLast(new LineBasedFrameDecoder(1024));
							arg.pipeline().addLast(new StringDecoder());*/
							arg.pipeline().addLast(new HelloClientHandler());
							System.out.println("--ChannelInitializer--");

						}
					});
			ChannelFuture f = client.connect(ip, port).sync();
			f.channel().closeFuture().sync();
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			work.shutdownGracefully();
		}
	}

}
